package com.company.news.ui.fragment.home;

import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.company.news.ChannelSelectedActivity;
import com.company.news.R;
import com.company.news.bean.Channel;
import com.company.news.common.MyLazyFragment;
import com.company.news.constants.Constant;
import com.company.news.listener.OnChannelListener;
import com.company.news.other.RefreshEvent;
import com.company.news.ui.MainActivity;
import com.company.news.ui.adapter.ChannelPagerAdapter;
import com.company.news.ui.fragment.NewsListFragment;
import com.company.news.ui.fragment.SimpleCardFragment;
import com.company.news.ui.fragment.channelfragment.ChannelDialogFragment;
import com.company.news.utils.PreUtils;
import com.company.news.utils.UIUtils;
import com.flyco.tablayout.SlidingTabLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yun.common.utils.SharePreferenceUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.jzvd.Jzvd;
import me.weyye.library.colortrackview.ColorTrackTabLayout;

/**
 * Created by Lovelin on 2019/5/31  OnChannelListener
 * <p>
 * 主页
 */
public class HomeFragment extends MyLazyFragment<MainActivity>   {
    @BindView(R.id.tv_01)
    TextView tv01;
    @BindView(R.id.tv_02)
    TextView tv_search;
    @BindView(R.id.tv_test_search)
    TextView tvTestSearch;
    @BindView(R.id.tab_channel)
    SlidingTabLayout mTabLayout;
    //ColorTrackTabLayout mTabLayout;
    @BindView(R.id.iv_operation)
    ImageView ivAddChannel;
    @BindView(R.id.vp_content)
    ViewPager mViewPager;
    Unbinder unbinder;

    private List<Channel> mSelectedChannels = new ArrayList<>();
    private List<Channel> mUnSelectedChannels = new ArrayList<>();
    private List<NewsListFragment> mChannelFragments = new ArrayList<>();
    private Gson mGson = new Gson();
    private ChannelPagerAdapter mChannelPagerAdapter;
    private String[] mChannelCodes;
    private String[] array;

    public static HomeFragment newInstance() {
        HomeFragment testFragmentA = new HomeFragment();
        Bundle bundle = new Bundle();
        testFragmentA.setArguments(bundle);
        return testFragmentA;
    }

    @Override
    protected int getLayoutId() {
        //解决第一次加载的时候不会更改颜色
        setFGStatusBarsColor(R.color.purple);
        return R.layout.fragment_home;
    }

    @Override
    protected int getTitleId() {
        return 0;
    }

    @Override
    protected void initView() {


    }

    @Override
    protected void initData() {
        initChannelData();
        initChannelFragments();
        ArrayList<String> titleList = new ArrayList<>();
        for (int i = 0; i < mSelectedChannels.size(); i++) {
            titleList.add(mSelectedChannels.get(i).title);
        }

        array = (String[]) titleList.toArray(new String[titleList.size()]);
        initListener();
    }

    private void initListener() {

        mChannelPagerAdapter = new ChannelPagerAdapter(mChannelFragments, mSelectedChannels, getChildFragmentManager());
        mViewPager.setAdapter(mChannelPagerAdapter);
        mTabLayout.setViewPager(mViewPager, array);
        mViewPager.setOffscreenPageLimit(mSelectedChannels.size());
        mTabLayout.post(new Runnable() {
            @Override
            public void run() {
                //设置最小宽度，使其可以在滑动一部分距离
                ViewGroup slidingTabStrip = (ViewGroup) mTabLayout.getChildAt(0);
                slidingTabStrip.setMinimumWidth(slidingTabStrip.getMeasuredWidth() + ivAddChannel.getMeasuredWidth());
            }
        });
        //隐藏指示器
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                //当页签切换的时候，如果有播放视频，则释放资源
                Jzvd.releaseAllVideos();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            handlerChangeUIAdapter();

        }
    };

    //频道选中之后回来 回调显示fragment和tablayout
    private void handlerChangeUIAdapter() {
        String selectedChannelJson = PreUtils.getString(Constant.SELECTED_CHANNEL_JSON, "");
        String unselectChannel = PreUtils.getString(Constant.UNSELECTED_CHANNEL_JSON, "");
        //之前添加过
        List<Channel> selectedChannel = mGson.fromJson(selectedChannelJson, new TypeToken<List<Channel>>() {
        }.getType());
        List<Channel> unselectedChannel = mGson.fromJson(unselectChannel, new TypeToken<List<Channel>>() {
        }.getType());
        mSelectedChannels.clear();
        mUnSelectedChannels.clear();
        mSelectedChannels.addAll(selectedChannel);
        mUnSelectedChannels.addAll(unselectedChannel);

        mChannelFragments.clear();

        mViewPager.setCurrentItem(2);
        ArrayList<String> titleList = new ArrayList<>();
        for (int i = 0; i < mSelectedChannels.size(); i++) {
            titleList.add(mSelectedChannels.get(i).title);
        }

        for (Channel channel : mSelectedChannels) {
//            NewsListFragment newsFragment = new NewsListFragment();
//            Bundle bundle = new Bundle();
//            bundle.putString(Constant.CHANNEL_CODE, channel.channelCode);
//            bundle.putBoolean(Constant.IS_VIDEO_LIST, channel.channelCode.equals(mChannelCodes[1]));//是否是视频列表页面,根据判断频道号是否是视频
//            newsFragment.setArguments(bundle);
//            mChannelFragments.add(newsFragment);//添加到集合中
//            mChannelFragments.add(SimpleCardFragment.getInstance(channel.title));//添加到集合中
            mChannelFragments.add(NewsListFragment.getInstance(channel.title));//添加到集合中

        }
        array = (String[]) titleList.toArray(new String[titleList.size()]);
        mChannelPagerAdapter = new ChannelPagerAdapter(mChannelFragments, mSelectedChannels, getChildFragmentManager());
        mViewPager.setAdapter(mChannelPagerAdapter);
        mTabLayout.setViewPager(mViewPager, array);
        mViewPager.setOffscreenPageLimit(mSelectedChannels.size());
        String tabIndex = (String) SharePreferenceUtil.get(getActivity(), SharePreferenceUtil.Tab_Selected_Index, "0");
        mTabLayout.setCurrentTab(Integer.parseInt(tabIndex));
        mChannelPagerAdapter.notifyDataSetChanged();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void TabRefreshEvent(RefreshEvent messageEvent) {
        mHandler.sendEmptyMessage(1);
    }

    /**
     * 初始化已选频道的fragment的集合
     */
    private void initChannelFragments() {
//        KLog.e("initChannelFragments");
        mChannelCodes = getResources().getStringArray(R.array.channel_code);
        for (Channel channel : mSelectedChannels) {
//            NewsListFragment newsFragment = new NewsListFragment();
//            Bundle bundle = new Bundle();
//            bundle.putString(Constant.CHANNEL_CODE, channel.channelCode);
//            bundle.putBoolean(Constant.IS_VIDEO_LIST, channel.channelCode.equals(mChannelCodes[1]));//是否是视频列表页面,根据判断频道号是否是视频
//            newsFragment.setArguments(bundle);
//            mChannelFragments.add(newsFragment);//添加到集合中
            mChannelFragments.add(NewsListFragment.getInstance(channel.title));//添加到集合中

        }
    }

    /**
     * 初始化已选频道和未选频道的数据
     */
    private void initChannelData() {
        String selectedChannelJson = PreUtils.getString(Constant.SELECTED_CHANNEL_JSON, "");
        String unselectChannel = PreUtils.getString(Constant.UNSELECTED_CHANNEL_JSON, "");

        if (TextUtils.isEmpty(selectedChannelJson) || TextUtils.isEmpty(unselectChannel)) {
            //本地没有title
            String[] channels = getResources().getStringArray(R.array.channel);
            String[] channelCodes = getResources().getStringArray(R.array.channel_code);
            //默认添加了全部频道
            for (int i = 0; i < channelCodes.length; i++) {
                String title = channels[i];
                String code = channelCodes[i];
                mSelectedChannels.add(new Channel(title, code));
            }

            selectedChannelJson = mGson.toJson(mSelectedChannels);//将集合转换成json字符串
//            KLog.i("selectedChannelJson:" + selectedChannelJson);
            PreUtils.putString(Constant.SELECTED_CHANNEL_JSON, selectedChannelJson);//保存到sp

        } else {
            //之前添加过
            List<Channel> selectedChannel = mGson.fromJson(selectedChannelJson, new TypeToken<List<Channel>>() {
            }.getType());
            List<Channel> unselectedChannel = mGson.fromJson(unselectChannel, new TypeToken<List<Channel>>() {
            }.getType());
            mSelectedChannels.addAll(selectedChannel);
            mUnSelectedChannels.addAll(unselectedChannel);
        }
    }

    public String getCurrentChannelCode() {
        int currentItem = mViewPager.getCurrentItem();
        return mSelectedChannels.get(currentItem).channelCode;
    }

    @Override
    public void onResume() {
        super.onResume();

    }

    @OnClick({R.id.tv_02, R.id.iv_operation})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_02:  //搜索

                break;
            case R.id.iv_operation:    //点击添加 channel
                startActivity(ChannelSelectedActivity.class);

//                ChannelDialogFragment dialogFragment = ChannelDialogFragment.newInstance(mSelectedChannels, mUnSelectedChannels);
//                dialogFragment.setOnChannelListener(this);
//                dialogFragment.show(getChildFragmentManager(), "CHANNEL");
//                dialogFragment.setOnDismissListener(new DialogInterface.OnDismissListener() {
//                    @Override
//                    public void onDismiss(DialogInterface dialog) {
//                        mChannelPagerAdapter.notifyDataSetChanged();
//                        mViewPager.setOffscreenPageLimit(mSelectedChannels.size());
////                        mTabLayout.setCurrentItem(mTabLayout.getSelectedTabPosition());
//                        ViewGroup slidingTabStrip = (ViewGroup) mTabLayout.getChildAt(0);
//                        //注意：因为最开始设置了最小宽度，所以重新测量宽度的时候一定要先将最小宽度设置为0
//                        slidingTabStrip.setMinimumWidth(0);
//                        slidingTabStrip.measure(0, 0);
//                        slidingTabStrip.setMinimumWidth(slidingTabStrip.getMeasuredWidth() + ivAddChannel.getMeasuredWidth());
//
//                        //保存选中和未选中的channel
//                        PreUtils.putString(Constant.SELECTED_CHANNEL_JSON, mGson.toJson(mSelectedChannels));
//                        PreUtils.putString(Constant.UNSELECTED_CHANNEL_JSON, mGson.toJson(mUnSelectedChannels));
//                    }
//                });
                break;
        }
    }


    // 使用沉浸式状态栏
    @Override
    public boolean isStatusBarEnabled() {
        return !super.isStatusBarEnabled();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
            savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


}
